package com.edais.service.imp;

import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.yunzhi.domain.ResultConstant;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.ActivityDao;
import com.edais.dao.ActivitySendMessageDao;
import com.edais.dao.KcodeChannelDao;
import com.edais.dao.UserDao;
import com.edais.domain.ActivitySendMessage;
import com.edais.domain.AfficheTab;
import com.edais.domain.BannerConfigTab;
import com.edais.domain.UserActivityKeyCode;
import com.edais.domain.UserActivityUpFrozenInfo;
import com.edais.domain.UserLDActivityInfo;
import com.edais.mina.TcpMinaClient;
import com.edais.persistence.gift.GiftPackageOrderMapper;
import com.edais.service.ActivityService;
import com.edais.service.RateRisesCouponsService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.FtpUtil;
import com.edais.util.JsonUtil;
import com.edais.util.StringUtil;
import com.edais.util.ThirdPartyEnvUtil;
import com.edais.util.RSAThirdParty.RSA;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;

import net.sf.json.JSONObject;

@Service

public class ActivityServiceImpl implements ActivityService {

	private static final Log logger = LogFactory.getLog(ActivityServiceImpl.class);

	@Autowired
	private ActivityDao activityDao;

	@Autowired
	private UserDao usersDao;

	@Autowired
	private ActivitySendMessageDao activitySendMessageDao;

	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;

	@Autowired
	private KcodeChannelDao kcodeChannelDao;

	@Autowired
	private GiftPackageOrderMapper giftPackageOrderMapper;

	/**
	 * 获取app版本信息
	 */
	@Override
	public ResultDTO getAppVersionInfo(Map<String, String> params) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		ResultDTO result;
		int totalSize = activityDao.getAppVersionInfoListCount(params);
		if (totalSize <= 0) {
			resultMap.put("list", new ArrayList());
			resultMap.put("totalNum", 0);
			resultMap.put("listSize", 0);
			return ResultConstant.SUCCESS;
		}
		List appVersionInfoList = activityDao.getAppVersionInfoList(params);

		if (appVersionInfoList == null || appVersionInfoList.size() <= 0) {
			resultMap.put("list", new ArrayList());
			resultMap.put("totalNum", totalSize);
			resultMap.put("listSize", 0);
			return new ResultDTO(ResultCode.SUCCESS, 0, totalSize, appVersionInfoList);
		}

		resultMap.put("list", appVersionInfoList);
		resultMap.put("totalNum", totalSize);
		resultMap.put("listSize", appVersionInfoList.size());
		return new ResultDTO(ResultCode.SUCCESS, appVersionInfoList.size(), totalSize, appVersionInfoList);
	}

	/**
	 * 
	 */
	@Override
	public List<BannerConfigTab> getBannerList(Map<String, Object> params)throws Exception {
		List<BannerConfigTab> bannerList = this.activityDao.getBannerList(params);
		return bannerList;
	}

	/**
	 * 
	 */
	@Override
	public List<Map<String, String>> getBannerListSEC() throws Exception {
		List<Map<String, String>> bannerList = new ArrayList();
		List retList = new ArrayList();
		bannerList = this.activityDao.getBannerListSEC();
		if (bannerList == null || bannerList.size() == 0 || (bannerList.size() == 1 && bannerList.get(0) == null)) {
		} else {
			for (int i = 0; i < bannerList.size(); i++) {
				Map tempMap = bannerList.get(i);
				Map<String, Object> retMap = new HashMap<String, Object>();
				retMap.put("ftpPath", tempMap.get("FTP_PATH"));
				retMap.put("bannerName", tempMap.get("BANNER_NAME"));
				retMap.put("sortNumber", tempMap.get("SORT_NUMBER"));
				retMap.put("requestURL", tempMap.get("REQUEST_URL"));
				retList.add(retMap);
			}
		}

		return retList;
	}

	/**
	 * 获取开关
	 */
	@Override
	public String findParamValueByName(String key) throws Exception {
		// 获取开关参数
		List<String> listStr = new ArrayList<String>();// 给sql传入的list参数
		// 验证K码开关 默认（1）从第三方服务器 2：DB
		listStr.add(key);
		// 去BL查询系统参数表
		List<Map<String, Object>> extractFeeRate = activityDao.queryParamName(listStr);
		if (extractFeeRate != null && extractFeeRate.size() > 0) {
			return (String) extractFeeRate.get(0).get("VALUE");
		}
		return null;
	}

	/**
	 * 验证K码合法性
	 */
	@Override
	public List<UserActivityKeyCode> findKeyCodeListByParm(Map<String, Object> map) throws Exception {
		return activityDao.findKeyCodeListByParm(map);
	}

	/**
	 * 获取k码使用数据
	 */
	@Override
	public List<UserLDActivityInfo> findActivityInfoByParm(Map<String, Object> map) throws Exception {
		return activityDao.findActivityInfoByParm(map);
	}

	@Override
	public void addActivityInfo(UserLDActivityInfo activityInfo) throws Exception {
		activityDao.addActivityInfo(activityInfo);
	}

	@Override
	public void updateActivityInfo(UserLDActivityInfo activityInfo) throws Exception {
		activityDao.updateActivityInfo(activityInfo);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String, Object> activityBidByBalance(String logInfo, Map<String, Object> map) throws Exception {
		logger.info(logInfo + "锁定K码尝试激活次数表");
		int lock = activityDao.updateForLock(Long.valueOf((Integer)map.get("userId")));
		logger.info(logInfo + "锁定K码尝试激活次数表结果：" + lock);
		
		Map<String, Object> retMap = new HashMap<String, Object>();
		String mobile = (String) map.get("mobile");
		String buyOrderId = "";
		// 赠送理财E350002(调用核心送理财)
		logger.info(logInfo + "赠送理财开始");
		Map<String, Object> resMap = buyLoan(map);
		if (resMap == null || !"00000".equals(resMap.get("rescode"))) {
			logger.error(logInfo + "赠送理财异常" + resMap.get("resmsg"));
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "赠送理财异常");
			return retMap;
		}
		logger.info(logInfo + "赠送理财理财成功");
		buyOrderId = resMap.get("orderId") + "";
		map.put("buyOrderId", buyOrderId);

		logger.info(logInfo + "赠送加息券开始");
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("mobile", mobile);
		reqMap.put("userId", null);
		reqMap.put("type", "7");
		this.rateRisesCouponsService.shareKNotifyAddCoupons(reqMap);
		logger.info(logInfo + "赠送加息券结束");

		retMap.put("orderId", buyOrderId);
		retMap.put("cpType", resMap.get("cpType"));
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		return retMap;
	}

	@Override
	@SuppressWarnings("rawtypes")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String, Object> kcodeGiftSend(String logInfo, Map<String, Object> map) throws Exception {
		logger.info(logInfo + "锁定K码尝试激活次数表");
		int lock = activityDao.updateForLock((Long)map.get("userId"));
		logger.info(logInfo + "锁定K码尝试激活次数表结果：" + lock);
		
		Map<String, Object> retMap = new HashMap<String, Object>();
		logger.info(logInfo + "赠送K码礼包开始");
		Map resMap = CommonUtil.invokeCore(logInfo, "kcodeGiftPackageSendService", map);
		if (resMap == null || !"00000".equals(resMap.get("rescode"))) {
			logger.error(logInfo + "赠送K码礼包异常" + resMap.get("resmsg"));
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "赠送K码礼包异常");
			return retMap;
		}
		logger.info(logInfo + "赠送K码礼包结束");
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		return retMap;
	}

	/**
	 * 活动送理财(E350002)
	 */
	public Map<String, Object> buyLoan(Map<String, Object> map) throws Exception {
		if (map == null || map.size() == 0) {
			return null;
		}

		String transCode = "E350002";

		String userId = (null == map.get("userId") ? "" : map.get("userId").toString());
		String buyAmount = (null == map.get("buyAmount") ? "" : map.get("buyAmount").toString());
		String lbAddAmount = (null == map.get("lbAddAmount") ? "" : map.get("lbAddAmount").toString());
		String kCode = map.get("kCode") == null ? "" : map.get("kCode").toString();
		String mobile = map.get("mobile") == null ? "" : map.get("mobile").toString();
		String cardNo = map.get("cardNo") == null ? "" : map.get("cardNo").toString();
		String channel = map.get("channel") == null ? "WX" : map.get("channel").toString();

		// 设置报文体报文数据
		Map<String, Object> pageModel = new HashMap<String, Object>();
		pageModel.put("userid", userId);
		pageModel.put("kCode", kCode);
		pageModel.put("cardNo", cardNo);
		pageModel.put("mobile", mobile);
		pageModel.put("amount", buyAmount);// 购买金额
		pageModel.put("lbAddAmount", lbAddAmount);// 购买金额
		pageModel.put("currency", "CNY");// 货币单位:CNY人民币，USD美元
		pageModel.put("cyclematchtype", 3);// 资金流转方式：1--收益循环投资—本息循环；2—收益每月返还—本金循环3—不循环
		pageModel.put("buyMedia", channel);// 购买媒介:1.网站；2.手机

		Map resmap = coreUse(userId, transCode, pageModel);
		return resmap;
	}

	/**
	 * 调用核心接口
	 */
	private Map coreUse(String userId, String transCode, Map<String, Object> pageModel) throws Exception {
		// 设置报文体报文数据
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModel);// 构建json字符串
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);

		if (StringUtils.isBlank(rtnStr)) {
			logger.debug("调用核心接口发生异常" + ",接口id：" + transCode);
			throw new Exception("调用核心接口发生异常" + ",接口id：" + transCode);
		}

		rtnStr = rtnStr.substring(8, rtnStr.length());
		// 转化json数据为页面模型数据格式
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(rtnStr, HashMap.class);

		return rtnMap;
	}

	/**
	 * 获取活动用标信息
	 */
	@Override
	public Map<String, Object> findActivityBidInfo() throws Exception {
		return activityDao.findActivityBidInfo();
	}

	@Override
	public String queryMyAccountDetail(Map<String, String> map) throws Exception {
		/**
		 * 调用核心接口 E350003查询我的账户详情信息
		 */
		String transCode = "E350003";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		queryCoreMap.put("userId", map.get("userId"));

		String jsonStr = CommonUtil.constructJsonStr(transCode, map.get("userId").toString(), queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		if (Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))) {
			JSONObject accountDetail = jsonObject.fromObject(jsonObject.get("accountDetail"));
			rtnMap.put("acctBalance", accountDetail.get("acctBalance"));
			rtnMap.put("amountSum", accountDetail.get("investAmountSum"));
		} else {
			logger.debug("=====E350003核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			rtnMap.put("acctBalance", "0");
			rtnMap.put("amountSum", "0");
		}
		return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
	}

	/**
	 * 根据卡号查询数据库是否存在K码
	 */
	@Override
	public Map<String, Object> checkKCodeByCardNo(Map<String, Object> map) throws Exception {
		Map<String, Object> kCodeMap = this.activityDao.findKeyCodeByCardNo(map);
		return kCodeMap;
	}

	/**
	 * 根据K码查询理财计划信息
	 */
	@Override
	public Map<String, Object> queryReturnFinanceInfoByKCode(Map<String, Object> map) throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<UserLDActivityInfo> activityInfoList = activityDao.findActivityInfoByParm(map);
		if (activityInfoList != null && activityInfoList.size() > 0) {
			UserLDActivityInfo activityInfo = activityInfoList.get(0);
			retMap.put("isActivation", 0);
			// 查询理财信息(理财是否到期，理财到期本金)
			String step1OrderId = activityInfo.getStep1_order_id();
			if (StringUtils.isNotBlank(step1OrderId)) {
				Map<String, Object> userMap = new HashMap<String, Object>();
				userMap.put("mobile", activityInfo.getMobile());

				BigDecimal expireAmount = BigDecimal.ZERO;
				String disposeState1 = new String();
				String isExpire = "1";
				String isFrozen = "0";
				// K码激活订单
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// 根据订单ID查询订单信息(判断是否有理财产品已到期)
				String transCode = "E320010";
				Map<String, Object> queryCoreMap = new HashMap<String, Object>();
				queryCoreMap.put("orderId", step1OrderId);
				String jsonStr = CommonUtil.constructJsonStr(transCode, null, queryCoreMap);
				String rtnStr = CommonUtil.getCoreValue(jsonStr);
				JSONObject jsonObject = JSONObject.fromObject(rtnStr);
				// 判断是否存在订单
				if (jsonObject != null && jsonObject.size() > 0) {
					Date investDate = sdf.parse(jsonObject.getString("INVEST_DATE"));
					// 判断是否到锁定期
					BigDecimal investAmount1 = new BigDecimal(jsonObject.getString("INVEST_AMOUNT"));
					disposeState1 = jsonObject.getString("DISPOSE_STATE");
					if (disposeState1.equals("3")) {
						expireAmount = expireAmount.add(investAmount1);
						isExpire = "0";
					}
					isFrozen = jsonObject.getString("FROZEN_STATUS").toString();
				}

				retMap.put("isExpire", isExpire);
				retMap.put("expireAmount", expireAmount.toString());
				retMap.put("isFrozen", isFrozen);
			} else {
				retMap.put("isExpire", 1);
				retMap.put("isFrozen", "0");
				retMap.put("expireAmount", "0");
			}

		} else {
			retMap.put("isActivation", 1);
		}

		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg_cn", "");
		return retMap;
	}

	/**
	 * 比较两个日期相差的天数
	 * 
	 * @param fDate
	 * @param oDate
	 * @return
	 */
	private int getIntervalDays(Date fDate, Date oDate) {
		Calendar aCalendar = Calendar.getInstance();
		aCalendar.setTime(fDate);
		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
		aCalendar.setTime(oDate);
		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
		return day2 - day1;
	}

	/**
	 * 发送联璧验证码
	 */
	@Override
	public Map<String, Object> sendKeyCode(Map<String, String> map) throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String message = map.get("message");
		String mobileNumber = map.get("mobileNumber");
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", message);
		paramMap.put("mobileListParams", mobileNumber);

		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.error("发送短信失败：http请求中断");
			throw new RuntimeException("验证码获取失败！");
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				// 系统异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			}
		}
		// 保存数据库信息
		// 查询是否存在已发送信息
		ActivitySendMessage newMessageInfo = new ActivitySendMessage();
		newMessageInfo.setMessage_text(message);
		newMessageInfo.setSetup_flag("LD");
		newMessageInfo.setSetup_result(1);
		newMessageInfo.setMobile_number(mobileNumber);
		this.activitySendMessageDao.addActivitySendMessage(newMessageInfo);

		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg_cn", "发送成功");
		return retMap;
	}

	/**
	 * 通过订单号更新订单状态
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> updateOrderStateByOrderId(Map<String, Object> map) throws Exception {

		Map<String, Object> retMap = new HashMap<String, Object>();

		String transCode = "E350004";
		String jsonStr = CommonUtil.constructJsonStr(transCode, map.get("userId").toString(), map);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		retMap.put("rescode", jsonObject.getString("rescode"));
		retMap.put("resmsg_cn", "");
		retMap.put("updateNum", jsonObject.getString("updateNum"));
		return retMap;
	}

	@Override
	public void updateActivityInfoIsValid(UserLDActivityInfo activityInfo) throws Exception {
		activityDao.updateActivityInfoIsValid(activityInfo);
	}

	/**
	 * 获得ftp配置信息，从参数配置表里面
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getSetting() throws Exception {
		Map<String, String> systemSettingMap = new HashMap<String, String>();

		/** 数据库参数 */
		// ftp的地址、用户名、密码
		String ftpUrl1 = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.FTP_ACTIVITYIMG_URL);
		String ftpUrl1_userLogin = usersDao
				.getSystemSettingValue(Consts.SystemSettingUpload.FTP_ACTIVITYIMG_URL_USERLOGIN);
		String ftpUrl1_password = usersDao
				.getSystemSettingValue(Consts.SystemSettingUpload.FTP_ACTIVITYIMG_URL_PASSWORD);
		// 图片路径 (原图)
		String ftpHeadImage_path = usersDao.getSystemSettingValue(Consts.SystemSettingUpload.FTP_ACTIVITYIMG_URL_PATH);
		// ftp的地址、用户名、密码
		systemSettingMap.put("ftpUrl1", ftpUrl1);
		systemSettingMap.put("ftpUrl1_userLogin", ftpUrl1_userLogin);
		systemSettingMap.put("ftpUrl1_password", ftpUrl1_password);
		systemSettingMap.put("ftpHeadImage_path", ftpHeadImage_path);

		// systemSettingMap.put("ftpUrl1", "192.168.16.222");
		// systemSettingMap.put("ftpUrl1_userLogin", "ftpuser");
		// systemSettingMap.put("ftpUrl1_password", "ftpuser");
		// systemSettingMap.put("ftpHeadImage_path", "img");

		/** 数据库参数 */
		System.out.println(systemSettingMap);
		return systemSettingMap;
	}

	/**
	 * 上传图片
	 */
	@Override
	@Transactional
	public String modifyPic(Map<String, Object> mapParam) throws Exception {
		String fileUrl = "";
		// 获取参数
		String fileName = (String) mapParam.get("fileName");// 文件名称
		// 获取输入流
		InputStream inputStreamTemp = (InputStream) mapParam.get("inputStream");// 文件
		// 获取配置参数
		Map<String, String> mapSystemSetting = this.getSetting();

		// 上传图片
		boolean logoName = FtpUtil.uploadFile3(mapSystemSetting.get("ftpUrl1"), // ip
				mapSystemSetting.get("ftpUrl1_userLogin"), // ftp登录名
				mapSystemSetting.get("ftpUrl1_password"), // ftp登录密码
				mapSystemSetting.get("ftpHeadImage_path"), // 文件上传的相对路径，紧跟在ip后面的地址字符串“/.../”
				fileName, // 文件名称
				inputStreamTemp);// 文件输入流
		if (logoName) {
			fileUrl = mapSystemSetting.get("ftpHeadImage_path") + "/" + fileName;
		}
		return fileUrl;
	}

	@Override
	public int updateActivityHistoryInfoByParm(Map<String, Object> map) throws Exception {

		return activityDao.updateActivityHistoryInfoByParm(map);
	}

	@Override
	public void addActivityHistoryInfo(Map<String, Object> map) throws Exception {
		activityDao.addActivityHistoryInfo(map);
	}

	@Override
	public Map<String, Object> queryActivityHistoryInfoByParm(Map<String, Object> map) throws Exception {
		return activityDao.queryActivityHistoryInfoByParm(map);
	}

	/**
	 * 通过订单号冻结/解冻订单
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> frozenOrderByOrderId(Map<String, Object> map) throws Exception {

		Map<String, Object> retMap = new HashMap<String, Object>();

		String transCode = "E360012";
		String jsonStr = CommonUtil.constructJsonStr(transCode, map.get("userId").toString(), map);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		retMap.put("rescode", jsonObject.getString("rescode"));
		retMap.put("resmsg_cn", jsonObject.getString("resmsg"));

		return retMap;
	}

	/**
	 * 记录卡号与型号的绑定关系
	 */
	// @Override
	// public Map<String, Object> addCardNoAndModelInfo(Map<String,String> map)
	// throws Exception {
	// Map<String,Object> resultMap = new HashMap<String,Object>();
	// String idcardNo = map.get("idcardNo");
	// String model = map.get("model");
	// String orderId = map.get("orderId");
	//
	// //查询是否存在此条信息
	// Map<String,Object> requestMap = new HashMap<String,Object>();
	//
	// requestMap.put("cardNo", idcardNo);
	//
	// UserActivityKeyCode userActivityKeyCode =
	// activityDao.queryUserActivityKeyCodeByCardNo(requestMap);
	//
	// String rescode = Consts.ERROR_CODE;
	// String resmsg = "数据记录失败！";
	// String resmsg_cn = "数据记录失败！";
	//
	// if(userActivityKeyCode!=null){
	// userActivityKeyCode.setOrder_id(orderId);
	// userActivityKeyCode.setModel(model);
	// int updateCount =
	// this.activityDao.updateUserActivityKeyCodeInfo(userActivityKeyCode);
	//
	// if(updateCount>0){
	// rescode = Consts.SUCCESS_CODE;
	// resmsg = "数据记录成功!";
	// resmsg_cn = "数据记录成功!";
	// }
	//
	// }else{
	// userActivityKeyCode = new UserActivityKeyCode();
	// userActivityKeyCode.setOrder_id(orderId);
	// userActivityKeyCode.setModel(model);
	// userActivityKeyCode.setCard_no(idcardNo);
	// userActivityKeyCode.setStatus("1");
	//
	// this.activityDao.addUserActivityKeyCodeInfo(userActivityKeyCode);
	//
	// if(userActivityKeyCode.getId()!=null){
	// rescode = Consts.SUCCESS_CODE;
	// resmsg = "数据记录成功!";
	// resmsg_cn = "数据记录成功!";
	// }
	// }
	//
	// resultMap.put("rescode", rescode);
	// resultMap.put("resmsg", resmsg);
	// resultMap.put("resmsg_cn", resmsg_cn);
	//
	// return resultMap;
	// }

	@Override
	public Map<String, Object> upFrozenByCardNo(Map<String, Object> map) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg", "");
		resultMap.put("resmsg_cn", "预冻结操作成功！");
		// 获取预冻结数据
		UserActivityUpFrozenInfo info = activityDao.queryUserUpForzenInfoByParm(map);
		if (info != null) {
			// 如果不是未处理的情况。则更新成 0 未处理
			if (!"0".equals(info.getIsValid())) {
				info.setIsValid("0");
				activityDao.updateUserUpForzenInfo(info);
			} else {
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg", "");
				resultMap.put("resmsg_cn", "该卡号已预冻结！");
			}
		} else {
			info = new UserActivityUpFrozenInfo();
			
			//礼包开关，开关开查询理财表，否则为理财
			String giftOnOff=findParamValueByName("gift_on-off");
			if(giftOnOff.equalsIgnoreCase("Y")){
				int count = giftPackageOrderMapper.queryCountKcodeLicai(map.get("card_no").toString());
				if (count > 0) {// 走的是理财
					info.setCardType("LICAI");
				} else {
					// 走礼包
					info.setCardType("LIBAO");
				}
			}else{
				info.setCardType("LICAI");
			}
			
			info.setCardNo(map.get("card_no").toString());
			info.setChannel(map.get("channel").toString());
			info.setIsValid("0");
			activityDao.addUserUpForzenInfo(info);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> upFrozenCancelByCardNo(Map<String, Object> map) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rescode", Consts.CHECK_CODE);
		resultMap.put("resmsg", "");
		resultMap.put("resmsg_cn", "该卡号未冻结！");

		// 获取预冻结数据
		UserActivityUpFrozenInfo info = activityDao.queryUserUpForzenInfoByParm(map);
		if (info != null && "0".equals(info.getIsValid())) {
			info.setIsValid("1");
			activityDao.updateUserUpForzenInfo(info);

			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg", "");
			resultMap.put("resmsg_cn", "解冻操作成功！");
		}
		return resultMap;
	}

	@Override
	public ResultDTO<BannerConfigTab>  getAcList(Map<String, Object> map) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		// 默认页
		Integer current = 1;
		Integer pageSize = 10;
		String currentStr = String.valueOf(map.get(Consts.Page.PAGE_CURRENT_NAME)); // 当前页数
		String pageSizeStr = String.valueOf(map.get(Consts.Page.PAGE_SIZE_NAME)); // 页大小
		if (null != currentStr && !("".equals(currentStr))) {
			current = Integer.parseInt(currentStr);
		}
		if (null != pageSizeStr && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		parms.put("beginRow", (current - 1) * pageSize);
		parms.put("endRow", pageSize);
		int totalNum = activityDao.getAcListCount();
		List<BannerConfigTab> acList = activityDao.getAcList(parms);
		ResultDTO<BannerConfigTab>  resultDTO = new ResultDTO<BannerConfigTab>(ResultCode.SUCCESS, pageSize ,totalNum, acList);
		return resultDTO;
		
	}

	@Override
	public UserActivityKeyCode queryUserActivityKeyCodeByCardNo(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		return activityDao.queryUserActivityKeyCodeByCardNo(map);
	}

	@Override
	public void addWbActivityKeyCodeData(Map<String, Object> map)
			throws SQLIntegrityConstraintViolationException, Exception {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date orderTime = fmt.parse(map.get("orderTime").toString());
		int channelId = activityDao.getActivityChannelIdByOrderTime(orderTime);
		map.put("channelId", channelId);
		activityDao.addWbActivityKeyCodeData(map);
	}

	/**
	 * 
	 * @Description: 送代金券
	 * @param @param
	 *            parammap
	 * @param @return
	 * @return Map<String,Object>
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-14
	 */
	@Async
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String, Object> sendVoucher(Map<String, Object> parammap, Map<String, Object> map) {
		// TODO Auto-generated method stub
		List<Map<String, Object>> paramsList = kcodeChannelDao.queryVoucherRule(parammap);
		Map<String, Object> retMap = new HashMap<String, Object>();
		if (null != paramsList && paramsList.size() > 0) {
			for (Map<String, Object> getparamMap : paramsList) {
				// 送代金券
				if (kcodeChannelDao.addVoucher(setVoucherMap(getparamMap, map)) == 0) {
					logger.error("添加代金券失败!");
					retMap.put("rescode", Consts.CHECK_CODE);
					retMap.put("resmsg", "");
					retMap.put("resmsg_cn", "添加代金券失败!");
					return retMap;
				}
			}
		}

		logger.info("添加代金券成功!");
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
		return retMap;
	}

	/**
	 * 
	 * @Description: 设置代金券信息
	 * @param @param
	 *            getparamMap
	 * @param @param
	 *            parammap
	 * @param @return
	 * @return Map<String,Object>
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-13
	 */
	private Map<String, Object> setVoucherMap(Map<String, Object> getparamMap, Map<String, Object> parammap) {
		// TODO Auto-generated method stub
		Map<String, Object> voucherMap = new HashMap<String, Object>();
		if (getparamMap != null) {

			Calendar currentDate = Calendar.getInstance();
			voucherMap.put("user_id", parammap.get("userId"));
			voucherMap.put("voucher_type_id", getparamMap.get("ID"));
			voucherMap.put("startdate", currentDate.getTime());
			String validityPeriod = "0";
			if (null != getparamMap.get("VALIDITY_PERIOD")) {
				validityPeriod = getparamMap.get("VALIDITY_PERIOD") + "";// 需要设置代金券类型表中有天数
			}
			currentDate.add(Calendar.DATE, Integer.parseInt(validityPeriod));

			voucherMap.put("enddate", currentDate.getTime());
			voucherMap.put("status", 0);
			voucherMap.put("orderid", null);
			voucherMap.put("voucher_amount", getparamMap.get("VOUCHER_AMOUNT"));
			voucherMap.put("investment_amount", getparamMap.get("INVESTMENT_AMOUNT"));
			voucherMap.put("source", "2");
			voucherMap.put("gift_staff", "1111");
			voucherMap.put("create_per", "1111");

		}

		return voucherMap;
	}

	// @Override
	// public void addKeycodeRecord(Map<String, Object> map) throws Exception {
	// // TODO Auto-generated method stub
	// kcodeChannelDao.addKeycodeRecord(map);
	// }
	//
	// @Override
	// public Map<String,Object> queryKeyCodeBykc(Map<String, Object> map)
	// throws Exception {
	// // TODO Auto-generated method stub
	// return kcodeChannelDao.queryKeyCodeBykc(map);
	// }
	//
	// @Override
	// public void updateKeyCodeRecordState(Map<String, Object> map)
	// throws Exception {
	// // TODO Auto-generated method stub
	// kcodeChannelDao.updateKeyCodeRecordState(map);
	// }
}
